package lv.solcraft.replication.server.model;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

public class OperStateUpdate {

    private static final int MAX_MESSAGE_LENGTH = 2000;

    private final long siteId;

    private final OperId operId;

    private final OperState state;

    private final String message;

    public OperStateUpdate(Long siteId, OperId oper, OperState state, String message) {
        super();
        this.siteId = siteId;
        this.operId = oper;
        this.state = state;
        this.message = StringUtils.left(message, MAX_MESSAGE_LENGTH);
    }

    public static OperStateUpdate fromOperSite(OperSite operSite) {
        return new OperStateUpdate(operSite.getSiteId(), operSite.getId(), operSite.getState(), operSite.getMessage());
    }

    public OperId getOperId() {
        return operId;
    }

    public OperState getState() {
        return state;
    }

    public String getMessage() {
        return message;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((operId == null) ? 0 : operId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final OperStateUpdate other = (OperStateUpdate) obj;
        if (operId == null) {
            if (other.operId != null)
                return false;
        } else if (!operId.equals(other.operId))
            return false;
        return true;
    }

    public long getSiteId() {
        return siteId;
    }

    @Override
    public String toString() {
        // TODO add to String!!!
        return super.toString();
    }

    public static OperStateUpdate fromJSON(long siteId, JSONObject json) {
        JSONObject jsonOperId = json.getJSONObject("id");
        OperId operId = new OperId(jsonOperId.getLong("originSiteId"), jsonOperId.getLong("originOperId"));
        OperState operState = OperState.valueOf(json.getString("state"));
        OperStateUpdate stateUpdate = new OperStateUpdate(siteId, operId, operState, json.getString("message"));
        return stateUpdate;
    }

    public JSONObject toJSON() {
        JSONObject json = new JSONObject();
        json.put("id", operId.toJSON());
        json.put("siteId", siteId);
        json.put("state", state);
        json.put("message", message);
        return json;
    }
}
